package com.huo.qq.pengyou;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Future;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.graphics.Point;

import com.huo.callable.OpenFileCallable;
import com.huo.common.Cmd;
import com.huo.common.DateUtil;
import com.huo.common.FileUtils;
import com.huo.common.StringUtil;
import com.huo.common.ThreadPool;
import com.huo.qq.common.States;
import com.huo.qq.entity.QQAccount;
import com.huo.qq.widget.TableViewerContentProvider;
import com.huo.qq.widget.TableViewerLabelProvider;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Table;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

@SuppressWarnings({"rawtypes","unchecked"})
public class Main {
	//日志
	private final static Log log = LogFactory.getLog(Main.class);
	/*
	 * 线程池
	 * 执行任务服务
	 */
	public static CompletionService<List> serv = new ExecutorCompletionService<List>(
			ThreadPool.getInstance().getExecutorService());
	/*
	 * 设置
	 */
	//是否输出操作信息
	private static boolean isPrint = true;
	/*
	 * 控件
	 */
	//qq号列表
	private Table table;
	//显示操作消息文本框
	private static StyledText txtMessage;
	//设置是否显示操作消息文本框
	private static Button chkIsPrint;
	//QQ信息表格
	private static CheckboxTableViewer qqTableViewer;
	//QQ状态下拉框
	private Combo cmbState;
	//登录按钮
	private static Button btnLogin;
	
	private static final FormToolkit formToolkit = new FormToolkit(Display.getDefault());
	
	/*
	 * 全局数据
	 */
	// 表格数据
	private static List<QQAccount> qqList;
	// qqID计数器
	private static int idCounter = 1;
	//读文件时的账号密码分隔符
	private static String splitSign = "----";
	
	private Text txtSplitSign;
	
	/**
	 * 退出应用程序
	 */
	public static void quit(){
		System.out.println("系统退出");
		System.exit(0);
	}
	
	/**
	 * 窗口初始化
	 * @return
	 */
	public void init(){
		print("初始化窗口");
		//初始化QQ状态下拉框
		initCmbState();
		//初始化数据表格
		if(initDataTable()) 
			print("初始化数据表格成功.");
		//选中显示操作消息
		chkIsPrint.setSelection(true);
		//初始化QQ全局数据列表
		qqList = new ArrayList<QQAccount>();
	}
	
	/**
	 * 初始化QQ状态下拉框
	 */
	public void initCmbState(){
		//获得QQ状态列表
		List<String> l = States.getStateList();
		String s[] = new String[l.size()];
		l.toArray(s);
		//设置下拉框数据
		cmbState.setItems(s);
		//在索引0处增加一项默认项
		cmbState.add("按状态勾选", 0);
		//设置默认选择第0个
		cmbState.select(0);
	}
	
	/**
	 * 初始化数据表格
	 * @return
	 */
	public boolean initDataTable() {
		boolean res = false;
		
		TableColumn choice = new TableColumn(table, SWT.CENTER);
		choice.setText("选择");
		choice.setWidth(70);

		TableColumn colQQ = new TableColumn(table, SWT.LEFT);
		colQQ.setText("号码");
		colQQ.setWidth(120);
		
		TableColumn colPassword = new TableColumn(table, SWT.LEFT);
		colPassword.setText("密码");
		colPassword.setWidth(80);
		
		TableColumn colState = new TableColumn(table, SWT.LEFT);
		colState.setText("状态");
		colState.setWidth(70);
		
		res = true;
		return res;
	}
	
	public static void print(String message){
		if(isPrint){
			StringBuffer mes = new StringBuffer().append("[")
					.append(DateUtil.getNowDateTime()).append("]").append(message)
					.append("\r\n");
			txtMessage.append(mes.toString());
		}
	}
	
	protected String getSplitSign() {
		String s = txtSplitSign.getText();
		if(StringUtil.isBlank(s)){
			s = "----";
		}
		return s;
	}
	
	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		final Shell shell = new Shell();
		shell.setImage(SWTResourceManager.getImage(Cmd.getProperty("user.dir") + "\\img\\logo.jpg"));
		shell.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent arg0) {
				//退出程序
				quit();
			}
		});
		shell.setLocation(new Point(350, 100));
		shell.setSize(728, 591);
		shell.setText("QQ朋友批量开通应用");
		
		Menu menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);
		
		MenuItem mnFile = new MenuItem(menu, SWT.CASCADE);
		mnFile.setText("文件(&F)");
		
		Menu menuItem = new Menu(mnFile);
		mnFile.setMenu(menuItem);
		
		MenuItem mnimImport = new MenuItem(menuItem, SWT.NONE);
		mnimImport.addSelectionListener(new SelectionAdapter() {
			public void fileChoose(){
				try {
					String[] pathArray = FileUtils.showFileDialog(shell,
							new String[] { "文本文件", "All Files (*.*)" },
							new String[] { "*.txt", "*.*" }, "c:\\");
					if (pathArray != null && pathArray.length > 0) {// 当数组有数据时为true
						for (String filePath : pathArray) {
							// 循环获得选择的多个文件，并将任务提交处理
							Callable<List> openFile = new OpenFileCallable(
									new File(filePath), getSplitSign());
							serv.submit(openFile);
						}
						
						//循环获得多个文件内容，加入qqList
						int plen = pathArray.length;
						for (int j = 0; j < plen; j++) {
							Future<List> task = serv.take();
							// 获取任务处理结果
							List<String[]> fl = task.get();
							for (int i = 0; i < fl.size(); i++) {
								// 将文件中读取到的数据添加到qqlist
								QQAccount acc = new QQAccount();
								acc.setId(String.valueOf(idCounter++));
								acc.setQq(fl.get(i)[0]);
								acc.setPassword(fl.get(i)[1]);
								acc.setState(States.NOLOGIN);
								qqList.add(acc);
							}
						}
						//内容器
						qqTableViewer.setContentProvider(new TableViewerContentProvider());
						//标签器
						qqTableViewer.setLabelProvider(new TableViewerLabelProvider());
						//在TableViewer内部为数据记录和TableItem之间的映射创建一个哈希表，加快TableItem和记录之间的查找速度
						qqTableViewer.setUseHashlookup(true);
						//设置数据
						qqTableViewer.setInput(qqList);
						print("账号导入成功");
					}
				} catch (Exception e) {
					e.printStackTrace();
					log.error("读取文件错误: " + e.getMessage());
				}
			}
			@Override
			public void widgetSelected(SelectionEvent e) {
				widgetDefaultSelected(e);
			}
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				fileChoose();
			}
		});
		mnimImport.setText("导入(&I)");
		
		MenuItem mnimExport = new MenuItem(menuItem, SWT.NONE);
		mnimExport.setText("导出(&O)");
		
		MenuItem mntmNewItem = new MenuItem(menuItem, SWT.SEPARATOR);
		mntmNewItem.setText("New Item");
		
		MenuItem mnimExit = new MenuItem(menuItem, SWT.NONE);
		mnimExit.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				quit();
			}
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				quit();
			}
		});
		mnimExit.setText("退出(&Q)");
		
		final Button chkAll = new Button(shell, SWT.CHECK);
		chkAll.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				//全选
				qqTableViewer.setAllChecked(chkAll.getSelection());
			}
		});
		chkAll.setBounds(52, 45, 13, 17);
		formToolkit.adapt(chkAll, true, true);
		qqTableViewer = CheckboxTableViewer.newCheckList(shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK);
		qqTableViewer.setAllGrayed(false);
		qqTableViewer.setAllChecked(false);
		table = qqTableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		table.setBounds(10, 39, 400, 413);
		
		txtMessage = new StyledText(shell, SWT.BORDER);
		txtMessage.setBounds(426, 39, 277, 413);
		formToolkit.adapt(txtMessage);
		formToolkit.paintBordersFor(txtMessage);
		
		chkIsPrint = new Button(shell, SWT.CHECK);
		//设置是否显示操作信息复选框
		chkIsPrint.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				if(chkIsPrint.getSelection()){
					//设置为输出操作信息
					isPrint = true;
					print("设置为输出操作信息");
					txtMessage.setVisible(true);
					shell.setSize(728, 575);
				}else{
					print("设置为不输出操作信息");
					isPrint = false;
					txtMessage.setVisible(false);
					shell.setSize(450, 575);
				}
			}
		});
		chkIsPrint.setBounds(10, 10, 98, 17);
		formToolkit.adapt(chkIsPrint, true, true);
		chkIsPrint.setText("显示操作信息");
		
		cmbState = new Combo(shell, SWT.NONE);
		cmbState.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				//获得状态下拉框选中的值
				String stValue = cmbState.getText();
				//循环判断qqList集合中哪些QQ的状态不是已登录
				for(int i=0;i<qqList.size();i++){
					QQAccount acc = qqList.get(i);
					if(stValue.equals(acc.getState())){//当QQ与下拉框选择的状态相同时，执行选中操作
						//勾选全选，便于之后的取消操作
						chkAll.setSelection(true);
						//勾选QQ
						qqTableViewer.setChecked(acc, true);
					}
				}
			}
		});
		cmbState.setItems(new String[] {});
		cmbState.setBounds(125, 7, 88, 25);
		formToolkit.adapt(cmbState);
		formToolkit.paintBordersFor(cmbState);
		
		Button btnDeleteSelection = new Button(shell, SWT.NONE);
		btnDeleteSelection.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				//获得选中的对象
				Object[] chkObjects = qqTableViewer.getCheckedElements();
				//获得选中的对象个数
				int olen = chkObjects.length;
				if (olen > 0) {
					// 删除表格中选中的对象
					qqTableViewer.remove(chkObjects);

					// 循环删除选中的对象
					for (int i = 0; i < olen; i++) {
						qqList.remove(chkObjects[i]);
					}
					print("删除成功.");
				}
			}
		});
		btnDeleteSelection.setBounds(230, 5, 80, 27);
		formToolkit.adapt(btnDeleteSelection, true, true);
		btnDeleteSelection.setText("删除选中");
		
		Group group = new Group(shell, SWT.NONE);
		group.setText("朋友网功能区");
		group.setBounds(10, 458, 400, 65);
		formToolkit.adapt(group);
		formToolkit.paintBordersFor(group);
		
		final String btnLoginText = "登录(&D)";
		btnLogin = new Button(group, SWT.NONE);
		btnLogin.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				//改变按钮文字,确定要执行的操作
				if (btnLogin.getText().indexOf('D') > 0) {
					//执行登录操作 
					btnLogin.setText("登录中..");
					
				} else {
					//停止执行登录
					btnLogin.setText(btnLoginText);
				}
			}
		});
		btnLogin.setText(btnLoginText);
		btnLogin.setBounds(24, 25, 80, 27);
		formToolkit.adapt(btnLogin, true, true);
		
		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setBounds(334, 10, 35, 17);
		formToolkit.adapt(lblNewLabel, true, true);
		lblNewLabel.setText("分隔符");
		
		txtSplitSign = new Text(shell, SWT.BORDER);
		txtSplitSign.setText("----");
		txtSplitSign.setBounds(375, 7, 35, 23);
		formToolkit.adapt(txtSplitSign, true, true);

		init();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Main window = new Main();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
